//
//  WmvMyTeamVM.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import UIKit
import RxRelay
import RxSwift

// MARK: - [WmvMyTeamVM]

class WmvMyTeamVM: WmcBaseVM {
    /// 列表数据(团队相册列表)
    let listData: BehaviorRelay<[WmcMediaTeamAlbumModel]?> = .init(value: nil)
    let error: BehaviorRelay<Error?> = .init(value: nil)
}

extension WmvMyTeamVM {
    /// 获取所有团队
    /// - Parameter page: 页码
    /// - Returns: description
    func getTeams(page: Int) {
        // 通过page的值判断是下拉还是上拉(可以用枚举)
        WmcHudManager.loading()
        WmcMediaTeamAlbumAPI.fetchTeamAlbumList().subscribe { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.updateRedDots(list)
            WmcHudManager.dismiss()
        } onError: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.toast(error)
            WmcHudManager.dismiss()
            weakSelf.error.accept(error)
        }.disposed(by: rx.disposeBag)
    }

    /// 获取相册最大ID数组 做比较
    /// - Returns: description
    func getTeamAlbumMaxIds() -> [String: Int] {
        guard let maxIds: [String: Int] = WmcUserdefault.object(forKey: .Tips.Home.teamAlbumMaxIds) else {
            return [:]
        }
        return maxIds
    }

    /// 更新红点
    /// - Parameter list: list description
    /// - Returns: description
    func updateRedDots(_ list: [WmcMediaTeamAlbumModel]) {
        self.listData.accept(list)
        WmcCloudAlbumInfoDBManager.query { [weak self] cacheList in
            guard let weakSelf = self else { return }

            for (_, model) in list.enumerated() {
                let idx = cacheList.firstIndex { cacheModel in
                    return model.albumId == cacheModel.albumId
                }
                if let idx = idx {
                    let cacheModel = cacheList[idx]
                    model.isShowRedDot = model.maxDbId > cacheModel.maxDbId
                } else if model.maxDbId > 0 {
                    model.isShowRedDot = true
                }
            }
            weakSelf.listData.accept(list)
        }
    }

    func updateAblumInfo(_ model: WmcMediaTeamAlbumModel) {
        WmcCloudAlbumInfoDBManager.query { list in
            let isContain = list.contains { item in
                return item.albumId == model.albumId
            }
            // 保存一下最新的照片id
            if isContain {
                WmcCloudAlbumInfoDBManager.update(albumId: model.albumId, latestPhotoId: model.maxDbId)
            } else {
                WmcCloudAlbumInfoDBManager.insert(albumId: model.albumId, latestPhotoId: model.maxDbId)
            }
        }
    }
}
